/*

This file is part of roomyak.

Copyright (C) 2008 Pixecur Technologies Incorporated (Esotera).
Visit Esotera at http://www.esoteras3.com
 
roomyak is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
 
roomyak is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with roomyak; see the file COPYING.  If not, write to 
Pixecur Technologies, 213-31 Peet Street, St. John's, NL, A1B 3W8. 
 
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
 
*/

package com.datasentinel.file;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author rickp
 *
 */
final public class FileBuilderFactory
{
	private static Logger logger = Logger.getLogger(FileBuilderFactory.class.getName());
	public static final String FILE_BUILDER_CLASS = "com.datasentinel.rooms.file.builder";
	private static FileBuilder fileBuilder;
	final public static FileBuilder createFileBuilder()
	{
		if (null == fileBuilder)
		{
			String configuredBuilder = System.getProperty(FILE_BUILDER_CLASS);
			if (null != configuredBuilder)
			{
				logger.log(Level.INFO, String.format("using configured file builder, class is [%s]",configuredBuilder));
				try
				{
					fileBuilder = createFileBuilder(configuredBuilder);
					logger.log(Level.INFO, String.format("successfully created configured file builder [%s]",fileBuilder));
				}
				catch(FileBuilderFactoryException e)
				{
					logger.log(Level.INFO, String.format("error while creating configured file builder [%s]",fileBuilder));
				}
			}
			if (null == fileBuilder)
			{
				logger.log(Level.INFO, String.format("using default file builder [%s]",fileBuilder));
				fileBuilder = new DefaultFileBuilder();
			}
		}
		return fileBuilder;
	}
	final public static FileBuilder createFileBuilder(String fileBuilderClassName) throws FileBuilderFactoryException
	{
		try
		{
			Class<?> clazz = Class.forName(fileBuilderClassName);
			Object newClassInstance = clazz.newInstance();
			if(newClassInstance instanceof FileBuilder)
			{
				return (FileBuilder) newClassInstance;
			}
			else throw new FileBuilderFactoryException("Class "+fileBuilderClassName+" is not of type FileBuilder");
		}
		catch(Exception e)
		{
			throw new FileBuilderFactoryException(e);
		}
	}
}
